package com.hopes.bizz.risk.transfer.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.hopes.bizz.risk.transfer.bean.dto.RiskDataDto;
import com.hopes.bizz.risk.transfer.bean.entity.RiskTransferDataEntity;
import com.hopes.bizz.risk.transfer.bean.entity.RiskTransferLogEntity;
import com.hopes.bizz.risk.transfer.constant.RiskConstant;
import com.hopes.bizz.risk.transfer.constant.RiskRequestType;
import com.hopes.bizz.risk.transfer.dto.RiskTransferData;
import com.hopes.bizz.risk.transfer.interceptor.RiskCompanyHolder;
import com.hopes.bizz.risk.transfer.mq.RiskDataProducer;
import com.hopes.bizz.risk.transfer.service.RiskReceiveService;
import com.hopes.bizz.risk.transfer.service.RiskTransferDataService;
import com.hopes.bizz.risk.transfer.service.RiskTransferLogService;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author lyb
 * @version 1.0
 * @date 2024/2/1 18:57
 */

@Service
@Slf4j
@AllArgsConstructor
public class RiskReceiveServiceImpl implements RiskReceiveService {

    private final RiskTransferLogService riskTransferLogService;

    private final RiskDataProducer riskDataProducer;

    private final RiskTransferDataService riskTransferDataService;

    @Override
    @SneakyThrows
    public String handlerRiskData(RiskDataDto riskDataDto, RiskRequestType requestType) {
        // 存日志
        RiskTransferLogEntity wrapper = new RiskTransferLogEntity();
        wrapper.setRequestType(requestType.getCode());
        wrapper.setErrorCount(0);
        wrapper.setTotalCount(0);
        wrapper.setRequestTime(LocalDateTime.now());
        wrapper.setStatus(RiskConstant.RISK_TRANSFER_HANDLER_STATUS_PROCESSING);
        wrapper.setOrgId(RiskCompanyHolder.getCompanyId());
        String batchId = UUID.randomUUID().toString();
        wrapper.setBatchId(batchId);
        riskTransferLogService.save(wrapper);
        // 存数据
        RiskTransferDataEntity riskTransferDataWrapper = new RiskTransferDataEntity();
        riskTransferDataWrapper.setBatchId(batchId);
        String data = riskDataDto.getData();
        riskTransferDataWrapper.setEncryptData(data);
        riskTransferDataWrapper.setOrgId(RiskCompanyHolder.getCompanyId());
        riskTransferDataService.save(riskTransferDataWrapper);

        // 发送消息
        RiskTransferData riskTransferData = new RiskTransferData(data, batchId);
        riskDataProducer.sendMsg(JSON.toJSONString(riskTransferData));
        return batchId;
    }
}
